/**
 * Created by Weizehua on 2017/1/21.
 */
import * as c from "crypto";
import {Hash, Hmac} from "crypto";

export class Crypto {
    static hmac(data: any, secret, algorithm): Promise<Buffer> {
        return Crypto.flushData(c.createHmac(algorithm, secret), data, 'hmac-' + algorithm);
    }

    static hash(data: any, algorithm): Promise<Buffer> {
        return Crypto.flushData(c.createHash(algorithm), data, 'hash-' + algorithm);
    }

    static randomBytes(length:number): Buffer {
        return c.randomBytes(length);
    }

    static ciphers(){
        return c.getCiphers();
    }

    static hashes() {
        return c.getHashes();
    }

    private static flushData(encoder: Hash | Hmac, data, algorithm): Promise<string|Buffer> {
        return new Promise<string|Buffer>((resolve, reject) => {
            encoder.on('readable', () => {
                let data = encoder.read();
                if (data) {
                    resolve(data);
                }
                else {
                    reject(new Error("Failed to perform encryption : " + algorithm));
                }
            });
            encoder.write(data);
            encoder.end();
        });
    }

}
